package loan.calc.util;

import java.io.*;


/**
 * @author v_ECD963
 */
public class CloneUtils {

    /**
     * 使用该方法的class及其父类必须分别继承Serializable，否则该方法会将类中属性值设置为属性声明的初始值
     * class为集合时，集合中的元素类需满足上述条件
     *
     * @param object 被复制的对象
     * @param <T>    对象类型
     * @return 新对象
     */
    public static <T> T deepClone(T object) {
        if (object == null) {
            return null;
        } else {
            ByteArrayOutputStream byteOut = null;
            ObjectOutputStream out = null;
            ByteArrayInputStream byteIn = null;
            ObjectInputStream in = null;
            try {
                byteOut = new ByteArrayOutputStream();
                out = new ObjectOutputStream(byteOut);
                out.writeObject(object);
                byteIn = new ByteArrayInputStream(byteOut.toByteArray());
                in = new ObjectInputStream(byteIn);
                @SuppressWarnings("unchecked")
                T cloneObject = (T) in.readObject();
                return cloneObject;
            } catch (IOException | ClassNotFoundException e) {
                throw new RuntimeException(e);
            } finally {
                close(byteOut, out, byteIn, in);
            }
        }
    }

    private static void close(Closeable... streams) {
        for (Closeable stream : streams) {
            if (stream != null) {
                try {
                    stream.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
